from sqlalchemy import select
from sqlalchemy.exc import DBAPIError, IntegrityError

from tinkoff_bot.core.exceptions.common import RepoError
from tinkoff_bot.core.exceptions.user import UserAlreadyExist, UserIdNotExist, UserTgIdNotExist
from tinkoff_bot.core.models.dto import UserDTO
from tinkoff_bot.infrastructure.database.converters.user import convert_db_model_to_user_dto
from tinkoff_bot.infrastructure.database.exception_mapper import exception_mapper
from tinkoff_bot.infrastructure.database.models import User
from tinkoff_bot.infrastructure.database.repositories.base import SQLAlchemyRepo


class UserReaderImpl(SQLAlchemyRepo):
    @exception_mapper
    async def get_user_by_id(self, user_id: int) -> UserDTO:
        user: User | None = await self._session.scalar(
            select(User).where(
                User.id == user_id,
            )
        )
        if not user:
            raise UserIdNotExist

        return convert_db_model_to_user_dto(user)

    @exception_mapper
    async def get_user_by_tg_id(self, user_tg_id: int) -> UserDTO | None:
        user: User | None = await self._session.scalar(
            select(User).where(
                User.telegram_id == user_tg_id,
            )
        )
        if not user:
            return None

        return convert_db_model_to_user_dto(user)

    @exception_mapper
    async def get_users(self) -> list[UserDTO]:
        """Получаем пользователей"""

        res = await self._session.scalars(select(User))
        users: list[User] = list(res)

        return [convert_db_model_to_user_dto(user) for user in users]


class UserRepoImpl(SQLAlchemyRepo):
    @exception_mapper
    async def acquire_user_by_tg_id(self, user_tg_id: int) -> User:
        """Получаем пользователя по telegram id"""

        user: User | None = await self._session.scalar(
            select(User).where(
                User.telegram_id == user_tg_id,
            )
        )
        if not user:
            raise UserTgIdNotExist

        return user

    @exception_mapper
    async def create_user(self, user: User) -> None:
        """Создаем пользователя"""

        self._session.add(user)
        try:
            await self._session.flush((user,))
        except IntegrityError as err:
            self._parse_error(err)

    @exception_mapper
    async def update_user(self, user: User) -> None:
        """Обновляем пользователя"""

        try:
            await self._session.merge(user)
        except IntegrityError as err:
            self._parse_error(err)

    @staticmethod
    def _parse_error(err: DBAPIError) -> None:
        match err.__cause__.__cause__.constraint_name:  # type: ignore
            case "uq_telegram_id":
                raise UserAlreadyExist
            case _:
                raise RepoError
